import React, { useCallback, useMemo } from "react";
import { FiltersItemsProps } from "./type";
import { h5ColorModule } from "../../Organisms/FilterModule.Organisms/styles/styled";
import CheckBox from "../../Atoms/CheckBox.Atom";
import { CheckboxAtomEnum } from "../../Atoms/CheckBox.Atom/enum";
import TextAtom from "../../Atoms/Text.Atom";
import TextAtomEnum from "../../Atoms/Text.Atom/enum";
import { useTranslation } from "react-i18next";

const FiltersItems: React.FC<FiltersItemsProps> = (props) => {
  const { t } = useTranslation();

  const { items, searchQuery, setSelectedFilters, selectedFilters, lengths } =
    props;

  const toggleFilter = useCallback(
    (index: number) => {
      setSelectedFilters((prevFilters: any) => {
        const newFilters = [...prevFilters];
        newFilters[index] = !newFilters[index];
        return newFilters;
      });
    },
    [setSelectedFilters]
  );

  const filteredItems = useMemo(() => {
    return items?.filter((item: any) =>
      item.toLowerCase().includes(searchQuery?.toLowerCase())
    );
  }, [items, searchQuery]);

  return (
    <div className="flex overflow-y-auto flex-col gap-3 max-h-40 px-[16px]">
      {filteredItems?.map((item: any, index: number) => (
        <div
          key={index}
          className="flex w-full justify-between items-center cursor-pointer"
          onClick={() => toggleFilter(index)}
        >
          <div className="flex gap-3">
            <CheckBox
              type={CheckboxAtomEnum.CHECKBOX}
              checked={selectedFilters[index]}
            />
            <TextAtom type={TextAtomEnum.enum_h5} className={h5ColorModule}>
              {item}
            </TextAtom>
          </div>
          <TextAtom type={TextAtomEnum.enum_h5} className={h5ColorModule}>
            {lengths && lengths[index]}
          </TextAtom>
        </div>
      ))}
      {!filteredItems.length && (
        <TextAtom
          type={TextAtomEnum.enum_h5}
          className="text-semibold font-medium"
        >
          {t("filterOrganism.searchItem")}
        </TextAtom>
      )}
    </div>
  );
};
export default React.memo(FiltersItems);
